import logging
import logging.handlers
import os
from datetime import datetime

def setup_logging():
    """
    设置应用程序日志配置
    """
    # 创建logs目录 - 使用绝对路径
    log_dir = os.path.abspath("logs")
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 设置日志格式
    log_format = "%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s"
    date_format = "%Y-%m-%d %H:%M:%S"
    
    # 创建格式化器
    formatter = logging.Formatter(log_format, date_format)
    
    # 获取根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    
    # 清除现有的处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 1. 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    
    # 2. 文件处理器 - 所有日志
    today = datetime.now().strftime("%Y-%m-%d")
    all_log_file = os.path.join(log_dir, f"app_{today}.log")
    
    # 确保日志文件存在
    if not os.path.exists(all_log_file):
        with open(all_log_file, 'w', encoding='utf-8') as f:
            f.write(f"# 日志文件创建于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
    
    file_handler = logging.handlers.RotatingFileHandler(
        all_log_file, 
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)
    
    # 3. 错误日志文件处理器
    error_log_file = os.path.join(log_dir, f"error_{today}.log")
    
    # 确保错误日志文件存在
    if not os.path.exists(error_log_file):
        with open(error_log_file, 'w', encoding='utf-8') as f:
            f.write(f"# 错误日志文件创建于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
    
    error_handler = logging.handlers.RotatingFileHandler(
        error_log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    root_logger.addHandler(error_handler)
    
    # 4. V2专用日志文件处理器
    v2_log_file = os.path.join(log_dir, f"v2_api_{today}.log")
    
    # 确保V2日志文件存在
    if not os.path.exists(v2_log_file):
        with open(v2_log_file, 'w', encoding='utf-8') as f:
            f.write(f"# V2 API日志文件创建于 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
    
    v2_handler = logging.handlers.RotatingFileHandler(
        v2_log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    v2_handler.setLevel(logging.INFO)
    v2_handler.setFormatter(formatter)
    
    # 创建V2专用日志记录器
    v2_logger = logging.getLogger("v2_api")
    v2_logger.setLevel(logging.INFO)
    v2_logger.addHandler(v2_handler)
    v2_logger.propagate = False  # 防止向根logger传播，避免重复打印
    v2_logger.addHandler(console_handler)  # 同时输出到控制台
    
    # 5. 外部API调用日志
    external_api_log_file = os.path.join(log_dir, f"external_api_{today}.log")
    external_api_handler = logging.handlers.RotatingFileHandler(
        external_api_log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    external_api_handler.setLevel(logging.INFO)
    external_api_handler.setFormatter(formatter)
    
    # 创建外部API专用日志记录器
    external_api_logger = logging.getLogger("external_api")
    external_api_logger.setLevel(logging.INFO)
    external_api_logger.addHandler(external_api_handler)
    external_api_logger.propagate = False  # 防止向根logger传播，避免重复打印
    external_api_logger.addHandler(console_handler)
    
    # 6. 数据库操作日志
    db_log_file = os.path.join(log_dir, f"database_{today}.log")
    db_handler = logging.handlers.RotatingFileHandler(
        db_log_file,
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    db_handler.setLevel(logging.INFO)
    db_handler.setFormatter(formatter)
    
    # 创建数据库专用日志记录器
    db_logger = logging.getLogger("database")
    db_logger.setLevel(logging.INFO)
    db_logger.addHandler(db_handler)
    db_logger.propagate = False  # 防止向根logger传播，避免重复打印
    db_logger.addHandler(console_handler)
    
    # 设置第三方库的日志级别
    logging.getLogger("uvicorn").setLevel(logging.INFO)
    logging.getLogger("uvicorn.access").setLevel(logging.INFO)
    logging.getLogger("fastapi").setLevel(logging.INFO)
    logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)
    
    logging.info("日志系统初始化完成")
    logging.info(f"日志文件目录: {os.path.abspath(log_dir)}")
    
    return {
        "v2_logger": v2_logger,
        "external_api_logger": external_api_logger,
        "db_logger": db_logger
    }

def get_logger(name: str = None):
    """
    获取指定名称的日志记录器
    """
    if name:
        return logging.getLogger(name)
    return logging.getLogger()

# 专用日志记录器获取函数
def get_v2_logger():
    """获取V2 API专用日志记录器"""
    return logging.getLogger("v2_api")

def get_external_api_logger():
    """获取外部API专用日志记录器"""
    return logging.getLogger("external_api")

def get_db_logger():
    """获取数据库专用日志记录器"""
    return logging.getLogger("database") 